package xyz.labmem.base.sys.config.redis

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.boot.autoconfigure.AutoConfigureBefore
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.StringRedisSerializer
import xyz.labmem.base.core.tool.JacksonObjectMapper

/**
 * @Author lty
 * @Date 2021/12/14 15:38
 */
@Configuration
@AutoConfigureBefore(RedisAutoConfiguration::class)
class RedisTemplateConfig {

    /**
     * 自定义Redis操作模板
     *
     * @param factory redis连接
     * @return Redis操作模板
     */
    @Bean
    fun redisTemplate(factory: RedisConnectionFactory): RedisTemplate<String, Any> {
        val template = RedisTemplate<String, Any>()
        template.setConnectionFactory(factory)
        val jackson2JsonRedisSerializer = Jackson2JsonRedisSerializer(
            Any::class.java
        )
        val om: ObjectMapper = JacksonObjectMapper().serializingObjectMapper()
        jackson2JsonRedisSerializer.setObjectMapper(om)
        template.keySerializer = StringRedisSerializer()
        template.hashKeySerializer = StringRedisSerializer()
        template.valueSerializer = jackson2JsonRedisSerializer
        template.hashValueSerializer = jackson2JsonRedisSerializer
        template.afterPropertiesSet()
        return template
    }

}